package service

import (
	"sdc/repository/db/model"

	"gorm.io/gorm"
)

type FavoriteService struct {
	db *gorm.DB
}

type FavoriteQuery struct {
	UserID     uint64
	Status     int8
	CategoryID uint64
	Page       int
	PageSize   int
}

// NewFavoriteService 创建收藏服务
func NewFavoriteService(db *gorm.DB) *FavoriteService {
	return &FavoriteService{db: db}
}

// CheckProjectStatus 检查项目状态
func (s *FavoriteService) CheckProjectStatus(projectID uint64) bool {
	var count int64
	s.db.Model(&model.Project{}).
		Where("id = ? AND status = ?", projectID, 1). // 1表示筹款中
		Count(&count)
	return count > 0
}

// IsFavorited 检查是否已收藏
func (s *FavoriteService) IsFavorited(userID, projectID uint64) bool {
	var count int64
	s.db.Model(&model.Favorite{}).
		Where("user_id = ? AND project_id = ?", userID, projectID).
		Count(&count)
	return count > 0
}

// AddFavorite 添加收藏
func (s *FavoriteService) AddFavorite(favorite *model.Favorite) error {
	return s.db.Transaction(func(tx *gorm.DB) error {
		// 创建收藏记录
		if err := tx.Create(favorite).Error; err != nil {
			return err
		}

		// 更新项目收藏数
		return tx.Model(&model.Project{}).
			Where("id = ?", favorite.ProjectID).
			UpdateColumn("favorite_count", gorm.Expr("favorite_count + ?", 1)).
			Error
	})
}

// CheckFavoriteOwner 检查收藏所有权
func (s *FavoriteService) CheckFavoriteOwner(favoriteID, userID uint64) bool {
	var count int64
	s.db.Model(&model.Favorite{}).
		Where("id = ? AND user_id = ?", favoriteID, userID).
		Count(&count)
	return count > 0
}

// RemoveFavorite 取消收藏
func (s *FavoriteService) RemoveFavorite(favoriteID uint64) error {
	return s.db.Transaction(func(tx *gorm.DB) error {
		// 获取收藏记录
		var favorite model.Favorite
		if err := tx.First(&favorite, favoriteID).Error; err != nil {
			return err
		}

		// 删除收藏记录
		if err := tx.Delete(&favorite).Error; err != nil {
			return err
		}

		// 更新项目收藏数
		return tx.Model(&model.Project{}).
			Where("id = ?", favorite.ProjectID).
			UpdateColumn("favorite_count", gorm.Expr("favorite_count - ?", 1)).
			Error
	})
}

// ListFavorites 收藏列表
func (s *FavoriteService) ListFavorites(query *FavoriteQuery) ([]model.Favorite, int64, error) {
	var favorites []model.Favorite
	var total int64

	db := s.db.Model(&model.Favorite{}).
		Where("user_id = ?", query.UserID)

	// 关联项目表进行筛选
	db = db.Joins("JOIN projects ON favorites.project_id = projects.id")

	// 按项目状态筛选
	if query.Status >= 0 {
		db = db.Where("projects.status = ?", query.Status)
	}

	// 按分类筛选
	if query.CategoryID > 0 {
		db = db.Where("projects.category_id = ?", query.CategoryID)
	}

	// 统计总数
	err := db.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (query.Page - 1) * query.PageSize
	err = db.Preload("Project").
		Preload("Project.Category").
		Offset(offset).Limit(query.PageSize).
		Order("favorites.created_at DESC").
		Find(&favorites).Error

	return favorites, total, err
}
